package com.example.demo.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.util.MD5Util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;

public class APIUtil {



	
	public static boolean pwd(String pwd, Map<String, String> map) {
		String url = APIUtil.formatUrlParam(map, "UTF-8", true);
		System.out.println("拼接字符串:" + url);
		/*
		 * StringBuffer s = new StringBuffer(); s.append(url); s.append("&");
		 * s.append("qaz123456");
		 */
		String stringToAscii = StringUtil.stringToAscii(url);
		System.out.println("stringToAscii:"+stringToAscii);
		String strMD5 = MD5Util.getStrrMD5(stringToAscii);
		System.out.println("MD5Util:"+strMD5);
		String yzpwd = strMD5.substring(0, 18);
		String upperCase = yzpwd.toUpperCase();
		System.out.println("生成sign:"+upperCase);
		if (upperCase.equals(pwd)) {
			return true;
		} else {
//			strMD5 = MD5Util.getStrrMD5(url);
//			yzpwd = strMD5.substring(0, 18);
//			if (yzpwd.equals(pwd)) {
//				return true;
//			}
			return false;
		}
	}

	public static void main(String[] args) {
		System.out.println(StringUtil.stringToAscii("a=1&b=2&c=3&appkey=123456"));
	}
	public static boolean isDoc(String str) {
       
        String reg=".*webjars.*";  //判断字符串中是否含有ll
        return str.matches(reg);
	}
	
	
	public static boolean isjs(String str) {
	       
        String reg=".*assets.*";  //判断字符串中是否含有ll
        return str.matches(reg);
	}
	

	public static Map<String, String> toMap(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		Map<?, ?> requestParams = request.getParameterMap();
		if (requestParams.isEmpty() || requestParams.equals("")) {

			BufferedReader bufferReaderBody = null;

			try {

				bufferReaderBody = new BufferedReader(request.getReader());

				String postData = bufferReaderBody.readLine();
				System.out.println("接收参数:" + postData);
				JSONObject jso = JSONObject.parseObject(postData);
				requestParams = JSONObject.toJavaObject(jso, Map.class);

			} catch (IOException e) {

				e.printStackTrace();

			} finally {

				if (bufferReaderBody != null) {
					try {
						bufferReaderBody.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

		for (Iterator<String> iter = (Iterator<String>) requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String valueStr = "";
			try {
				String[] values = (String[]) requestParams.get(name);
			
				valueStr = values[0];
				

//				  for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1)
//				  ? valueStr + values[i] : valueStr + values[i] + ","; }

			} catch (Exception e) {
				try{
                    valueStr = (String) requestParams.get(name);
                }catch (Exception es){
                    valueStr = JSON.toJSONString(requestParams.get(name));
                }

				
			}

			// 乱码解决，这段代码在出现乱码时使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		return params;
	}

	public static String formatUrlParam(Map<String, String> param, String encode, boolean isLower) {
		String params = "";
		Map<String, String> map = param;

		try {
			List<Entry<String, String>> itmes = new ArrayList<Entry<String, String>>(map.entrySet());

			// 对所有传入的参数按照字段名从小到大排序
			// Collections.sort(items); 默认正序
			// 可通过实现Comparator接口的compare方法来完成自定义排序
			Collections.sort(itmes, new Comparator<Entry<String, String>>() {
				@Override
				public int compare(Entry<String, String> o1, Entry<String, String> o2) {
					// TODO Auto-generated method stub
					return (o1.getKey().toString().compareTo(o2.getKey()));
				}
			});

			// 构造URL 键值对的形式
			StringBuffer sb = new StringBuffer();
			for (Entry<String, String> item : itmes) {
				if (StringUtils.isNotBlank(item.getKey())) {
					String key = item.getKey();
					if(key.equals("sign")){
						continue;
					}
					if(key.equals("token")){
						continue;
					}
					String val = item.getValue();

					if (isLower) {
						sb.append(key + "=" + val);
					} else {
						sb.append(key + "=" + val);
					}
					sb.append("&");

					/* val = URLEncoder.encode(val, encode); */

				}
			}

			/*
			 * for (Map.Entry<String, String> item : itmes) { if
			 * (StringUtils.isNotBlank(item.getKey())) { String key =
			 * item.getKey(); String val = item.getValue();
			 * if(key.equals("token")){ if (isLower) { sb.append(key +
			 * "=qaz123456"); } else { sb.append(key + "=qaz123456"); }
			 * sb.append("&"); }
			 * 
			 * 
			 * val = URLEncoder.encode(val, encode);
			 * 
			 * } }
			 */
			sb.append("appkey=ljv");
			params = sb.toString();
			if (!params.isEmpty()) {
				params = params.substring(0, params.length());
			}
		} catch (Exception e) {
			return "";
		}
		return params;
	}


}
